import axios from 'axios'
import { getServerBaseURL } from '@/config'
import { axiosInterceptorFilterEmptyData } from 'train-fe-component'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
import { delLocalStorage, getLocalStorage } from '@/storage'
import { history } from 'umi'
import type { ReportType } from '@/pages/report/entry/interface'
import { Toast } from 'antd-mobile'

export const http = axios.create({
    baseURL: getServerBaseURL(true),
    headers: {
        'Content-Type': 'application/json',
        'X-Site-Domain': location.host,
    },

    /** 处理 */
    validateStatus: status => {
        return (status >= 200 && status < 300) || status === 401
    },
})

/**
 * 添加 token
 */
http.interceptors.request.use((config: AxiosRequestConfig) => {
    const queryParams = history.location.query as {
        type?: ReportType
    }

    if (getLocalStorage('ACCESS_TOKEN')) {
        const token = getLocalStorage('ACCESS_TOKEN')
        config.headers = {
            ...config.headers,
            Authorization: 'Bearer ' + token,
        }
    }

    if (getLocalStorage('SITE_DOMAIN')) {
        const domain = getLocalStorage('SITE_DOMAIN')
        config.headers = {
            ...config.headers,
            ['X-Site-Domain']: domain,
        }
    }

    if (queryParams?.type === 'other') {
        config.headers = {
            ...config.headers,
            Secret: getLocalStorage('SECRET_CODE') ?? '',
        }
    }

    return config
})

/**
 * 过滤params对象中空字符串字段
 */
http.interceptors.request.use(
    axiosInterceptorFilterEmptyData({
        methodList: ['get'],
    }),
)

http.interceptors.response.use((res: AxiosResponse) => {
    const processRes = { ...res, ...res.data }
    return processRes
})

http.interceptors.response.use((res: AxiosResponse) => {
    console.log(res)
    if (res?.code === 401) {
        delLocalStorage('LOGIN_INFO')
        delLocalStorage('ACCESS_TOKEN')
        history.push({ pathname: '/login' })
        Toast.show({
            icon: 'fail',
            content: res?.msg || '',
        })
        return {
            data: {},
        }
    } else if (res?.code !== 200) {
        Toast.show({
            icon: 'fail',
            content: res?.msg || '',
        })
        return {
            data: {},
        }
    }

    return res
})
